package com.ronglian.register_mini_program.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ronglian.register_mini_program.model.RegisterOrder;
import com.ronglian.register_mini_program.model.RegisterUser;
import com.ronglian.register_mini_program.model.web.ActivityDetailBody;
import com.ronglian.register_mini_program.model.web.RequiredInfo;
import com.ronglian.register_mini_program.result.ResultBody;
import com.ronglian.register_mini_program.service.ActivityService;
import com.ronglian.register_mini_program.service.OrderService;
import com.ronglian.register_mini_program.service.UserService;
import com.ronglian.register_mini_program.util.JsonUtils;
import com.ronglian.register_mini_program.util.ObjecctUtil;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/export")
@Api(tags = "excel导出", description = "excel导出")
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successful — 请求已完成"),
        @ApiResponse(code = 400, message = "请求中有语法问题，或不能满足请求"),
        @ApiResponse(code = 401, message = "未授权客户机访问数据"),
        @ApiResponse(code = 404, message = "服务器找不到给定的资源；文档不存在"),
        @ApiResponse(code = 500, message = "服务器不能完成请求")}
)
public class ExcelController {

    /**
     * Excel表格导出接口
     * http://localhost:8080/ExcelDownload
     *
     * @param response response对象
     * @throws IOException 抛IO异常
     */
    @Autowired
    UserService userService;
    @Autowired
    ActivityService activityService;
    @Autowired
    OrderService orderService;
    @Autowired
    ObjectMapper mapper;

    @ApiOperation(value = "excel表格导出", notes = "excel表格导出")
    @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "activity_id", value = "活动id", required = true)
    @RequestMapping(value = "/ExcelDownload/{activity_id}", method = RequestMethod.GET)
    public ResultBody excelDownload(@PathVariable("activity_id") Integer activity_id, HttpServletResponse response) throws IOException {
        try {
            int arrange_index = 0;
            //表头数据
//        String[] header = {"ID", "姓名", "性别", "年龄", "地址", "分数"};
            //查询活动信息
            ActivityDetailBody activity = activityService.findByPrimaryKey(activity_id);
            String json = activity.getRequired_info();
            //获取要填写的用户信息json数据中的title
//        List<RequiredInfo> requiredInfos = mapper.readValue(json, List.class);
            List<RequiredInfo> requiredInfos = JsonUtils.jsonToList(json, RequiredInfo.class);

            /**
             * 哦我们再
             */


            //拿到数据信息,保存key value  "type":"button" "title":"姓名"
            //        String[] header = {"input", "input", "input", "input", "button", "input"};
            String[] header_key = new String[requiredInfos.size()];
            //        String[] header_value = {"ID", "姓名", "性别", "年龄", "地址", "分数"};
            String[] header_value = new String[requiredInfos.size()];
            //        String[] header_property = {"id", "name", "sex", "age", "address", "score"};
            String[] header_property = new String[requiredInfos.size()];
            int count = 0;

            for (int i = 0; i < requiredInfos.size(); i++) {


                //如果本次属性与下次属性一致，则不复制
                String type = requiredInfos.get(i).getType();
                String name = requiredInfos.get(i).getName();
                String property = requiredInfos.get(i).getProperty();
                if (property.equals("arrange")) {

                    count += 1;
                    if (count > 1) {
                        continue;
                    } else {
                        header_key[i] = type;
                        header_value[i] = "安排";
                        header_property[i] = "arrange";
                        arrange_index = i;
                    }

                } else {
                    header_key[i] = type;
                    header_value[i] = name;
                    header_property[i] = property;
                }
            }
            System.out.println(header_key);
            System.out.println(header_value);

            //这个属性数组要验证用户的属性
            List<String> propertys = Arrays.asList(header_property);

            //报名数据内容========报名人的信息
//        String[] student1 = {"1", "小红", "女", "23", "成都青羊区", "96"};
//        String[] student2 = {"2", "小强", "男", "26", "成都金牛区", "91"};
//        String[] student3 = {"3", "小明", "男", "28", "成都武侯区", "90"};


            //声明一个工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();

            //生成一个表格，设置表格名称为"学生表"
            HSSFSheet sheet = workbook.createSheet(activity.getActivity_title() + "报名表");

            //设置表格列宽度为10个字节
            sheet.setDefaultColumnWidth(10);

            //创建第一行表头
            HSSFRow headrow = sheet.createRow(0);

            //遍历添加表头(下面模拟遍历学生，也是同样的操作过程)
            for (int i = 0; i < header_value.length; i++) {
                //创建一个单元格
                HSSFCell cell = headrow.createCell(i);

                //创建一个内容对象
                HSSFRichTextString text = new HSSFRichTextString(header_value[i]);

                //将内容对象的文字内容写入到单元格中
                cell.setCellValue(text);
            }
            List<RegisterOrder> orders = orderService.findOrderListWithActivityId(activity_id);
            if (orders != null && orders.size() > 0) {
                for (int i = 0; i < orders.size(); i++) {
                    String arrange = "";
                    //此订单的安排arrange
//                    if (!StringUtils.isBlank(orders.get(i).getArrange())) {
//                        arrange = orders.get(i).getArrange();
//
//                    }

                    //每次遍历用户对象生成对应的数组对象，遍历生成表格
                    String[] info_arr = new String[requiredInfos.size()];
//                    info_arr[arrange_index] = arrange;
                    //模拟遍历结果集，把内容加入表格
                    //模拟遍历-----用户报名
                    //用过验证用户是否声明过该属性，然后给数组赋值
                    String openid = orders.get(i).getOpen_id();
                    RegisterUser user = userService.findByOpenId(openid);
                    if (user != null) {
                        //遍历property属性是否存在
                        Field[] fields = user.getClass().getDeclaredFields();
                        for (int f = 0; f < fields.length; f++) {
                            //字段
                            Field field = fields[f];
                            //判断属性数组中是否包含该字段
                            boolean bool = propertys.contains(field.getName());
                            //如果为真就往数组里存数据，然后与属性的index对应
                            //遍历数组，验证数组是否存在该属性，
                            //1.先看在不在，然后再获取索引，然后给student该index处赋值
                            if (bool) {

                                int index = propertys.indexOf(field.getName());
                                Object object = ObjecctUtil.getFieldValueByName(field.getName(), user);
                                if (field.getName().equals("sex")) {
                                    if (String.valueOf(object).equals("1")) {
                                        object = "男";
                                    } else if (String.valueOf(object).equals("0")) {
                                        object = "女";
                                    } else {
                                        object = "";
                                    }
                                }
                                info_arr[index] = String.valueOf(object);
                            }

                        }

                    }


                    HSSFRow row = sheet.createRow(i + 1);
                    int arr_lenth = info_arr.length;
                    if (count>0){
                        arr_lenth = arr_lenth-(count-1);
                    }

                    for (int h = 0; h < arr_lenth; h++) {
                        HSSFCell cell = row.createCell(h);
                        System.out.println("打印一下单元格数据====="+info_arr[h]);
                        String cell_Str = info_arr[h];
                        if ( StringUtils.isEmpty(cell_Str)||cell_Str.equals("null")){
                            System.out.println("我要换了null,hahahhahaha==========");
                            info_arr[h]="无";
                        }
                        HSSFRichTextString text = new HSSFRichTextString(info_arr[h]);
                        cell.setCellValue(text);
                    }

                }

            }

            //准备将Excel的输出流通过response输出到页面下载
            //八进制输出流
            response.setContentType("application/octet-stream");

            //这后面可以设置导出Excel的名称，此例中名为student.xls
            response.setHeader("Content-disposition", "attachment;filename=student.xls");

            //刷新缓冲
            response.flushBuffer();

            //workbook将Excel写入到response的输出流中，供页面下载
            workbook.write(response.getOutputStream());

            return null;

        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBody("500", "excel表格导出失败！");
        }


    }

}
